package com.java110.mall.acct.cmd.payment;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.payment.PaymentOrderDto;
import com.java110.dto.payment.PaymentPoolDto;
import com.java110.intf.acct.IPaymentPoolV1InnerServiceSMO;
import com.java110.mall.acct.payment.IPaymentBusiness;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.factory.ApplicationContextFactory;
import com.java110.utils.util.Assert;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;

/**
 * 统一支付接口(演示用)
 */
@Java110Cmd(serviceCode = "payment.testCashier")
public class TestCashierCmd extends Cmd {


    private static final Logger logger = LoggerFactory.getLogger(TestCashierCmd.class);

    protected static final String DEFAULT_PAYMENT_ADAPT = "wechatPaymentFactory";// 默认微信通用支付

    public static final String DOMAIN_WECHAT_PAY = "WECHAT_PAY";
    public static final String DOMAIN_WECHAT_STORE = "WECHAT_STORE";


    // 微信服务商支付开关
    public static final String WECHAT_SERVICE_PAY_SWITCH = "WECHAT_SERVICE_PAY_SWITCH";

    public static final String WECHAT_PAY_PLATFORM = "PAY_PLATFORM";


    //开关ON打开
    public static final String WECHAT_SERVICE_PAY_SWITCH_ON = "ON";


    @Autowired
    private IPaymentPoolV1InnerServiceSMO paymentPoolV1InnerServiceSMOImpl;


    /**
     * 校验
     *
     * @param event   事件对象
     * @param context 请求报文数据
     * @param reqJson
     * @throws CmdException
     */

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        String env = MappingCache.getValue(MappingConstant.ENV_DOMAIN, "ENV_PAY");
        if (!"DEV".equals(env)) {
            throw new CmdException("此接口不能调用");
        }

        Assert.hasKeyAndValue(reqJson, "business", "未包含业务");
        Assert.hasKeyAndValue(reqJson, "cashierUserId", "未包含收银人员");
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺ID");

        context.getReqHeaders().put("user-id", reqJson.getString("cashierUserId"));
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        logger.debug(">>>>>>>>>>>>>>>>支付参数报文,{}", reqJson.toJSONString());
        String appId = context.getReqHeaders().get("app-id");
        String userId = reqJson.getString("cashierUserId");


        //1.0 查询当前支付的业务

        IPaymentBusiness paymentBusiness = ApplicationContextFactory.getBean(reqJson.getString("business"), IPaymentBusiness.class);

        if (paymentBusiness == null) {
            throw new CmdException("当前支付业务不支持");
        }

        //2.0 相应业务 下单 返回 单号 ，金额，
        PaymentOrderDto paymentOrderDto = paymentBusiness.unified(context, reqJson);
        paymentOrderDto.setAppId(appId);
        paymentOrderDto.setUserId(userId);


        logger.debug(">>>>>>>>>>>>>>>>支付业务下单返回,{}", JSONObject.toJSONString(paymentOrderDto));

        paymentBusiness.notifyPayment(paymentOrderDto, reqJson);
        JSONObject param = new JSONObject();
        param.put("code", "100");
        param.put("msg", "演示环境不触发支付");
        context.setResponseEntity(new ResponseEntity(JSONObject.toJSONString(param), HttpStatus.OK));

    }

    /**
     * 计算适配器
     *
     * @param business
     * @param reqJson
     * @return
     */
    private String computeAdapt(String business, JSONObject reqJson) {

        String shopId = reqJson.getString("shopId");

        String paySwitch = MappingCache.getValue(DOMAIN_WECHAT_STORE, WECHAT_PAY_PLATFORM);
        if (WECHAT_SERVICE_PAY_SWITCH_ON.equals(paySwitch)) {
            reqJson.put("paymentPoolId", "999999");
            return null;
        }

        //todo 按小区查询 支付信息
        PaymentPoolDto paymentPoolDto = new PaymentPoolDto();
        paymentPoolDto.setShopId(shopId);
        paymentPoolDto.setPayType(PaymentPoolDto.PAY_TYPE_COMMUNITY);
        paymentPoolDto.setState("Y");
        List<PaymentPoolDto> paymentPoolDtos = paymentPoolV1InnerServiceSMOImpl.queryPaymentPools(paymentPoolDto);
        if (paymentPoolDtos == null || paymentPoolDtos.isEmpty()) {
            throw new IllegalArgumentException("商家店铺未配置支付信息");
        }

        reqJson.put("paymentPoolId", paymentPoolDtos.get(0).getPpId());
        return paymentPoolDtos.get(0).getBeanJsapi();
    }

    /**
     * 临时车场景处理
     *
     * @param business
     * @param shopId
     * @return
     */
    private PaymentPoolDto ifPaymentPlatformBusiness(String business, String shopId) {


        String paySwitch = MappingCache.getValue(DOMAIN_WECHAT_STORE, WECHAT_PAY_PLATFORM);
        if (!WECHAT_SERVICE_PAY_SWITCH_ON.equals(paySwitch)) {
            return null;
        }

        PaymentPoolDto paymentPoolDto = new PaymentPoolDto();
        paymentPoolDto.setPpId("999999");
        paymentPoolDto.setBeanJsapi("wechatPaymentFactory");
        return paymentPoolDto;
    }

}
